package model;

import java.util.ArrayList;
import java.util.List;

public class GameThread extends Thread {
	private AbstractPlayer p1, p2;
	private Connected4Game game;
	private boolean enableStatistics;
	private List<Double> times1, times2;

	public GameThread(AbstractPlayer p1, AbstractPlayer p2,
			Connected4Game game, boolean enableStatistics) {
		super();
		this.p1 = p1;
		this.p2 = p2;
		this.game = game;
		this.enableStatistics = enableStatistics;
		times1 = new ArrayList<Double>();
		times2 = new ArrayList<Double>();
	}

	@Override
	public void run() {

		while (game.getGameState() == model.State.PLAYING) {
			if (p1.isTurnToPlay()) {
				long startTime = System.nanoTime();
				int col = p1.executeMove();
				if (enableStatistics) {
					long estimatedTime = System.nanoTime() - startTime;
					double sec = (double) (estimatedTime) / (Math.pow(10, 9));
					times1.add(sec);
				}
				
				if (col != -1) {
					game.update(col, p1);
					if (game.getGameState() == model.State.PLAYING)
						game.callNextPlayerTurn();
				}
			} else if (p2.isTurnToPlay()) {
				
				long startTime = System.nanoTime();
				
				int col = p2.executeMove();
				
				if (enableStatistics) {
					long estimatedTime = System.nanoTime() - startTime;
					double sec = (double) (estimatedTime) / (Math.pow(10, 9));
					times2.add(sec);
				}
				
				if (col != -1) {
					game.update(col, p2);
					if (game.getGameState() == model.State.PLAYING)
						game.callNextPlayerTurn();
				}
			}

//			try {
//				Thread.sleep(200);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
		}
	}

	public List<Double> getTimes1() {
		return times1;
	}

	public List<Double> getTimes2() {
		return times2;
	}
}
